package com.hjt.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hjt.common.constant.ProductConstant;
import com.hjt.common.utils.PageUtils;
import com.hjt.common.utils.Query;
import com.hjt.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.hjt.gulimall.product.dao.AttrDao;
import com.hjt.gulimall.product.dao.AttrGroupDao;
import com.hjt.gulimall.product.dao.CategoryDao;
import com.hjt.gulimall.product.entity.*;
import com.hjt.gulimall.product.entity.AttrVo;
import com.hjt.gulimall.product.service.AttrService;
import com.hjt.gulimall.product.service.CategoryService;
import com.hjt.gulimall.product.vo.AttrResponseVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    AttrAttrgroupRelationDao relationDao;

    @Autowired
    AttrGroupDao attrGroupDao;

    @Autowired
    CategoryDao categoryDao;

    @Autowired
    CategoryService categoryService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    // 保存属性，还要添加属性与属性分组的关系
    @Transactional
    @Override
    public void saveAttr(AttrVo attr) {
        //  保存基本数据
        AttrEntity entity = new AttrEntity();
        BeanUtils.copyProperties(attr, entity);
        baseMapper.insert(entity);
        // 销售属性才需要保存与属性分组的关联关系
        if (attr.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            // 保存 属性与属性分组的关联关系
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            relationEntity.setAttrId(entity.getAttrId());
            relationDao.insert(relationEntity);
        }
    }

    // 分页查询属性信息，查询时还要查出属性所在 【分组名称】 以及 【商品分类名称】
    @Override
    public PageUtils queryBaseAttrPage(String catelogId, Map<String, Object> params, String attrType) {
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();

        // 判断属性类型
        wrapper = wrapper.eq("attr_type",ProductConstant.AttrEnum.ATTR_TYPE_BASE.getMessage().equalsIgnoreCase(attrType) ? ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode():ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());
        // 先查出基本信息
        // 1.分类id
        if (!catelogId.equals("0")) {
            wrapper.eq("catelog_id", catelogId);

        }
        // 2.属性id精确查询和属性名字模糊查询
        String key = (String) params.get("key");
        if (StringUtils.hasLength(key)) {
            wrapper.and(obj -> {
                obj.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );
        PageUtils pageUtils = new PageUtils(page);
        List<AttrEntity> record = page.getRecords();

        // 再设置 【分组名称】 以及 【商品分类名称】 信息
        List<AttrResponseVo> responseVoList =  record.stream().map(entity -> {
            AttrResponseVo responseVo = new AttrResponseVo();
            BeanUtils.copyProperties(entity, responseVo); // 封装基本信息
            // 查询分组和分类的名字

            // 基本属性才查询分组名字
            if (ProductConstant.AttrEnum.ATTR_TYPE_BASE.getMessage().equalsIgnoreCase(attrType)) {
                // 1.从属性-属性分组表中查出分组的id
                QueryWrapper<AttrAttrgroupRelationEntity> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("attr_id", entity.getAttrId());
                // 2.根据分组id查询分组的名字
                AttrAttrgroupRelationEntity relationEntity = relationDao.selectOne(queryWrapper);
                if (relationEntity != null) {
                    Long groupId = relationEntity.getAttrGroupId();
                    String groupName = attrGroupDao.selectById(groupId).getAttrGroupName();
                    responseVo.setGroupName(groupName);
                }
            }

            // 3.根据分类id查询分类的名字
            CategoryEntity categoryEntity = categoryDao.selectById(entity.getCatelogId());
            if (categoryEntity != null) {
                responseVo.setCatelogName(categoryEntity.getName());
            }
            return responseVo;
        }).collect(Collectors.toList());
        pageUtils.setList(responseVoList);
        return pageUtils;
    }

    // 查询属性详细信息，包括 catelogPath": [2, 34, 225] //分类完整路径
    @Override
    public AttrResponseVo getAttrInfo(Long attrId) {
        // 查询封装基本信息
        AttrEntity attrEntity = this.getById(attrId);
        AttrResponseVo attrResponseVo = new AttrResponseVo();
        BeanUtils.copyProperties(attrEntity, attrResponseVo);


        // 基本属性，查询分组id
        if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            QueryWrapper<AttrAttrgroupRelationEntity> wrapper = new QueryWrapper<>();
            wrapper.eq("attr_id", attrId);
            AttrAttrgroupRelationEntity relationEntity = relationDao.selectOne(wrapper);
            if (relationEntity != null) {
                attrResponseVo.setAttrGroupId(relationEntity.getAttrGroupId());
            }
        }

        // 查询分类路径
        Long[] catelogPath = categoryService.findCatelogPath(attrEntity.getCatelogId());
        attrResponseVo.setCatelogPath(catelogPath);
        return attrResponseVo;
    }

    // 修改属性信息
    @Transactional
    @Override
    public void updateAttrInfo(AttrVo attr) {
        // 封装基本信息
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);

        // 修改基本信息
        baseMapper.updateById(attrEntity);

        // 基本属性才添加分组关联
        if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            Integer count = relationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
            if (count > 0) {
                // 1.修改分组关联
                AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
                relationEntity.setAttrGroupId(attr.getAttrGroupId());
                relationEntity.setAttrId(attr.getAttrId());
                relationDao.update(relationEntity,
                        new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
            } else {
                // 2.新增分组关联
                AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
                relationEntity.setAttrGroupId(attr.getAttrGroupId());
                relationEntity.setAttrId(attr.getAttrId());
                relationDao.insert(relationEntity);
            }
        }

    }

    /**
     * 获取分组下的所有属性
     * @param attrGroupId
     * @return
     */
    @Override
    public List<AttrEntity> getRelationAttr(Long attrGroupId) {
        // 通过属性-分组关系表查找到所有的属性id
        Wrapper<AttrAttrgroupRelationEntity> wrapper = new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrGroupId);
        List<Long> attrIdList = relationDao.selectList(wrapper).stream()
                .map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList());

        if (attrIdList.size() == 0) {
            return null;
        }
        // 通过属性id查找属性
        return (List<AttrEntity>) this.listByIds(attrIdList);
    }

    /**
     * 获取当前分组没有关联的属性
     * @param attrGroupId
     * @param params
     * @return
     */
    @Override
    public PageUtils getNoRelationAttr(String attrGroupId, Map<String, Object> params) {

        // 1.只能查找当前分组 所属 分类 的属性
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrGroupId);
        // 2.只能关联没有被其他分组关联的属性
        List<Long> attrGroupIdList = null;
        if (attrGroupEntity != null) {
            Long catelogId = attrGroupEntity.getCatelogId(); // 所在分类的id
            // 2.1 找到当前分组所属分类下的所有分组id
            attrGroupIdList = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId))
                              .stream().map(AttrGroupEntity::getAttrGroupId).collect(Collectors.toList());
        }

        // 2.2 找到这些分组关联的所有属性id
        QueryWrapper<AttrAttrgroupRelationEntity> wrapper = new QueryWrapper<AttrAttrgroupRelationEntity>();
        if (attrGroupIdList != null && attrGroupIdList.size() >0) {
            wrapper.in("attr_group_id", attrGroupIdList);
        }
        List<Long> attrIdList = relationDao.selectList(wrapper).stream()
                .map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList());

        // 2.3 去除这些id之外的所有基本属性
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>().eq("attr_type",ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
        if (attrIdList.size() >0) {
            queryWrapper.notIn("attr_id", attrIdList);
        }
        String key = (String) params.get("key");
        if (StringUtils.hasLength(key)) {
            queryWrapper.and(obj -> {
                obj.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params),queryWrapper);
        return new PageUtils(page);
    }

    // 查找出所有 【可被检索的】属性id
    @Override
    public List<Long> selectSearchableAttrIds(List<Long> attrIdList) {

        List<Long> searchableAttrIds = baseMapper.selectSearchableAttrIds(attrIdList);
//        List<Long> searchableAttrIds = baseMapper.selectBatchIds(attrIdList).stream()
//                .filter(attrEntity -> attrEntity.getSearchType() == 1)
//                .map(AttrEntity::getAttrId)
//                .collect(Collectors.toList());
        return searchableAttrIds;
    }

}